package agent

import (
	"context"
	"encoding/json"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/agentClient/rpc"
	"github.com/zeromicro/go-zero/core/logc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserRebatesLevelListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 会员返佣等级--列表
func NewGetUserRebatesLevelListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserRebatesLevelListLogic {
	return &GetUserRebatesLevelListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetUserRebatesLevelListLogic) GetUserRebatesLevelList(req *types.UserRebatesLevelListReq) (resp *types.UserRebatesLevelList, err error) {
	// 用户返佣等级--列表
	rpcReq := &rpc.GetUserRebatesLevelListReq{
		UserID:   req.UserId,
		Page:     req.Page,
		PageSize: req.Size,
	}

	rpcResp, err := l.svcCtx.AgentRPC.GetUserRebatesLevelList(l.ctx, rpcReq)
	if err != nil {
		logc.Error(l.ctx, err)
		return nil, err
	}

	_data := make([]types.UserRebatesLevelInfo, len(rpcResp.Data))
	for _i, _row := range rpcResp.Data {
		var _usedIssueNumber []int
		if _row.UsedIssueNumber != "" {
			err := json.Unmarshal([]byte(_row.UsedIssueNumber), &_usedIssueNumber)
			if err != nil {
				return nil, err
			}
		}
		_data[_i] = types.UserRebatesLevelInfo{
			Id:              _row.ID,
			UserId:          _row.UserID,
			Level:           _row.Level,
			FeeRate:         _row.FeeRate,
			AvailableDays:   _row.AvailableDays,
			UsedDays:        _row.UsedDays,
			UsedIssueNumber: _usedIssueNumber,
			Status:          _row.Status,
			CreatedAt:       _row.CreatedAt,
			UpdatedAt:       _row.UpdatedAt,
		}
	}
	resp = &types.UserRebatesLevelList{
		Page:      int32(rpcResp.Page),
		PageSize:  int32(rpcResp.PageSize),
		Total:     rpcResp.Total,
		TotalPage: rpcResp.TotalPage,
		List:      _data,
	}

	return
}
